﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Threading.Tasks;

namespace DAL
{
    /// <summary>
    /// 数据访问类
    /// </summary>
    public class DBHelper
    {
        // 数据库连接字符串-以下二选一，请自行选择和修改参数
        // Windows身份验证
        public static string strCnn = "server=.;database=Demo;Integrated Security=true";
        //private const string strCnn = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;";

        // SQLServer身份验证 
        //private const string strCnn = "server=.;database=TestDB;uid=sa;pwd=1;";

        // 创建连接对象
        private static SqlConnection cnn = new SqlConnection(strCnn);

        /// <summary>
        /// 打开连接
        /// </summary>
        private static void Open()
        {
            try
            {
                if (cnn.State == ConnectionState.Closed)
                {
                    cnn.Open();
                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        private static void Close()
        {
            try
            {
                if (cnn.State == ConnectionState.Open)
                {
                    cnn.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }

        }

        /// <summary>
        /// 执行SQL，返回一个数据表
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet ExucuteSQL_DataTable(string sql)
        {
            try
            {
                // 创建适配器对象
                SqlDataAdapter da = new SqlDataAdapter(sql, cnn);
                Open(); // 打开连接
                DataSet ds = new DataSet();
                da.Fill(ds); // 填充数据到数据表

                return ds;
            }
            catch (Exception)
            {
                return null; // 如果发生异常，返回null 
            }
            finally
            {
                Close(); // 关闭连接
            }

        }

        /// <summary>
        /// 执行SQL，增删改数据 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteSQL(string sql)
        {
            try
            {
                // 创建SqlCommand对象
                SqlCommand cmm = new SqlCommand(sql, cnn);
                Open(); // 打开连接

                return cmm.ExecuteNonQuery();

            }
            catch (Exception)
            {
                return -1; // 当返回值是-1时，表示发生异常执行失败
            }
            finally
            {
                Close(); // 关闭连接
            }
        }

    }
}
